package br.com.blog.conversores;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

@org.jboss.seam.annotations.faces.Converter
@BypassInterceptors
@Name("cpfConverter")
public class CpfConverter implements Converter{

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String valor) throws ConverterException {
        /*
         * Não formatado
         */
        String cpf = valor;
        if (cpf != null && !cpf.equals("")) {
            cpf = valor.replace(".", "").replace("-", "");
        }
        if (cpf.length() != 11) {
            throw new ConverterException("Formato inválido");
        }
        return cpf;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object valor) throws ConverterException {
        /*
         * Formatado
         */
        String cpf = (String) valor;
        if (cpf == null || cpf.length() != 11) {
            throw new ConverterException("Formato inválido");
        }

        cpf = cpf.substring(0, 3) + "."
                + cpf.substring(3, 6) + "."
                + cpf.substring(6, 9) + "-"
                + cpf.substring(9);
        return cpf;
    }

}
